package cn.itsource.basic.interceptor;

import cn.itsource.user.domain.Logininfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.coyote.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("4444444444444444");
        // 1.从header中获取token
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)){
            // 从reids中根据token获取用户数据
          Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
            if (null != logininfo){
                /// redis 续命 给当前的key 设置过期时间
                redisTemplate.expire(token,30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        // 返回false 是拦截请求
        return false;
    }
}
